package com.yjd.comm.servlet;

import com.yjd.comm.base.exception.BaseException;
import com.yjd.comm.base.model.ResultModel;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.vo.Constant.ResultEnum;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName: DispatcherServletWrap
 * @Description: spring手机端分发器包装类
 * @author ready likun_557@126.com
 * @date 2014-11-3 下午10:54:23
 */
public class MobileDispatcherServletWrap extends DispatcherServlet {

	private static Logger logger = Logger
			.getLogger(MobileDispatcherServletWrap.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		inService(request, response);
	}

	protected void inService(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			super.service(request, response);
		} catch (Exception e) {
			// ajax异常处理
			ResultModel resultModel = ResultModel.createResultModel();
			if (e.getCause() instanceof BaseException) {
				logger.error(e.getMessage() + ",请求地址:" + ServletUtil.getRequestFullUrl(request), e);
				BaseException oe = (BaseException) e.getCause();
				resultModel.setResult(ResultEnum.ERROR);
				resultModel.setCode(oe.getCode());
				resultModel.setMessage(oe.getMessage());
			} else {
				logger.error(e.getMessage() + ",请求地址:" + ServletUtil.getRequestFullUrl(request), e);
				resultModel.setResult(ResultEnum.ERROR);
				resultModel.setMessage(FrameUtil.getResource("sysEx.00001"));
			}
			try {
				ServletUtil.outputJsonMessage(request, response,
						resultModel.toMap());
			} catch (Exception e1) {
				throw new RuntimeException(FrameUtil.getResource("sysEx.00001"));
			}
		}
	}

}
